﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpNewFeatures
{
    internal class CsharpDemo4 : CsharpDemoBase
    {
        public override void Run()
        {
            Test1();
            Test2();
            Test3();
        }

        CancellationTokenSource cts = new CancellationTokenSource();
        public void Test1()
        {
            TaskFactory factory = new TaskFactory(
            cts.Token,
            TaskCreationOptions.PreferFairness,
            TaskContinuationOptions.ExecuteSynchronously,
            TaskScheduler.Default);
            var t2 = factory.StartNew(() => DoWork());
            cts.Dispose();
        }
        void DoWork()
        {
            Thread.Sleep(10);
            Console.WriteLine("Hello");
        }


        public void Test2()
        {

            Task[] tasks = new Task[2];
            String[] files = null;
            String[] dirs = null;
            String docsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            tasks[0] = Task.Factory.StartNew(() => files = Directory.GetFiles(docsDirectory));
            tasks[1] = Task.Factory.StartNew(() => dirs = Directory.GetDirectories(docsDirectory));

            Task.Factory.ContinueWhenAll(tasks, completedTasks =>
            {
                Console.WriteLine("{0} contains: ", docsDirectory);
                Console.WriteLine("   {0} subdirectories", dirs.Length);
                Console.WriteLine("   {0} files", files.Length);
            });

        }

        public void Test3()
        {
            Task<string[]>[] tasks = new Task<string[]>[2];
            String docsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            tasks[0] = Task<string[]>.Factory.StartNew(() => Directory.GetFiles(docsDirectory));
            tasks[1] = Task<string[]>.Factory.StartNew(() => Directory.GetDirectories(docsDirectory));

            Task.Factory.ContinueWhenAll(tasks,
                completedTasks =>
                {
                    Console.WriteLine("{0} contains: ", docsDirectory);
                    Console.WriteLine("   {0} subdirectories", tasks[1].Result.Length);
                    Console.WriteLine("   {0} files", tasks[0].Result.Length);
                });
        }
    }
}
